package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import net.sf.json.JSONObject
import org.slf4j.Logger
import org.slf4j.LoggerFactory

/**
 * @Description: 根据配置同步数据表，然后调用经营|电销|短信接口执行任务下发或者短信创建
 * @author: tian*
 * @date 2021-12-16 11:00:00
 */

public class autoTaskThread implements EliteThreadInvoke {
    private static final Logger log = LoggerFactory.getLogger(autoTaskThread.class);

    //任务下发主要方法
    public int doCallBack(EliteBean eliteBean, String content) {
        log.debug("待处理名单线程Guid：" + content);
        boolean restatus = false;
        try {

            //将当前线程更新为执行中状态1
            String upThreadStatus = "update Elitethread set expand='1' where content='" + content + "'";
            eliteBean.update(upThreadStatus, "dataSource");

            //步骤一：查询线程号是否存在配置且已经启用
            String checkConfigureSql = "SELECT ifnull(p1.rec_guid,'') as rec_guid,p1.task_state,p1.task_starttime,p1.task_endtime,now() AS time, Date_format(p1.task_starttime,'%H:%i:%s') as time2, Date_format(now(),'%H:%i:%s') as time3,Date_format(p1.task_endtime,'%H:%i:%s') as time4    from pa_sms_task_batch p1 where p1.task_state = '0' and p1.rec_guid='" + content + "'";
            List configureList = eliteBean.chaxun_sql(checkConfigureSql, "dataSource");
            String check_rec_guid = configureList.get(0).get("rec_guid"); // 配置表-线程号
            String check_starttime = configureList.get(0).get("task_starttime"); // 配置表-开始执行时间
            String check_endtime = configureList.get(0).get("task_endtime"); // 配置表-最后执行时间
            String time = configureList.get(0).get("time"); //当前数据库时间

            String time2 = configureList.get(0).get("time2"); //开始执行时间时分秒
            String time3 = configureList.get(0).get("time3"); //当前时间时分秒
            String time4 = configureList.get(0).get("time4"); //结束执行时间时分秒

            //1.当前时间>最后执行时间 2.配置表线程号为空时 3.任务停止时，如重新开启界面需要添加线程号至线程表，此三种情况直接停止线程后续执行
            if ((time > check_endtime) || KHUtil.isNull(check_rec_guid)) {
                String deleteThreadSql = "delete from Elitethread where content='" + content + "'";
                eliteBean.update(deleteThreadSql, "dataSource");
                return 1;
            }


            log.debug("配置表-线程号:"+check_rec_guid+"|开始执行时间时分秒:"+time2+"|"+"结束执行时间时分秒："+time4+"|当前时间时分秒："+time3);
            if (time2<=time3&&time3<=time4){

            //步骤二：根据传入的线程号查询是否在对应启用时间范围，在则判断是否可执行
            String TaskSql1 = "SELECT ifnull(p1.rec_guid,'') as rec_guid,ifnull(p2.content,'') as content,ifnull(p1.dateselect,'') as dateselect,ifnull(p2.execution_cycle,'') as execution_cycle,ifnull(p2.prev_fire_time,'') as prev_fire_time,ifnull(p2.next_fire_time,'') as next_fire_time,ifnull(p1.table_name,'') as table_name,ifnull(p1.identification,'') as identification,ifnull(p1.identification_content,'') as identification_content,now() AS time,ifnull(p1.task_time,'') as task_time,ifnull(p2.execution_interval,'') as execution_interval,ifnull(p1.task_type,'') as task_type,p1.trading_day,p2.task_starttime as plan_task_starttime,p2.task_endtime as plan_task_endtime FROM pa_sms_task_batch p1 LEFT JOIN ( SELECT content, execution_cycle, prev_fire_time, next_fire_time, execution_interval,task_starttime,task_endtime FROM pa_execution_plan WHERE content = '" + content + "' ORDER BY prev_fire_time DESC LIMIT 1 ) p2 ON p1.rec_guid = p2.content WHERE p1.rec_guid = '" + content + "' AND now()>= p1.task_starttime AND now()<= p1.task_endtime AND p1.task_state = '0' LIMIT 1";
            List taskList = eliteBean.chaxun_sql(TaskSql1, "dataSource");
            if (taskList.size() > 0) {
                //进入这里的都是启用的并且在开始时间和结束时间内的数据
                String rec_guid = taskList.get(0).get("rec_guid"); // 配置表-线程号
                String dateselect = taskList.get(0).get("dateselect"); // 配置表-执行周期
                String time_interval = taskList.get(0).get("task_time"); //配置表-执行间隔时间
                String table_name = taskList.get(0).get("table_name"); // 配置表-数据表名
                String task_type = taskList.get(0).get("task_type"); //配置表-任务类型
                String identification = taskList.get(0).get("identification"); // 配置表-任务标识字段
                String identificationContent = taskList.get(0).get("identification_content"); //配置表-任务标识内容
                String trading_day = taskList.get(0).get("trading_day"); // 配置表-非交易日是否执行
                String contentPlan = taskList.get(0).get("content");  // 计划表-线程号
                String execution_cycle = taskList.get(0).get("execution_cycle"); // 计划表-执行周期
                String execution_interval = taskList.get(0).get("execution_interval"); //计划表-执行间隔时间
                String prev_fire_time = taskList.get(0).get("prev_fire_time"); // 上次执行时间


                //判断非交易日是否可执行
                List freedateList = eliteBean.chaxun_sql("Select R1.Freedate, R1.datetype, R1.Next_Freedate, Datediff(R1.Next_Freedate, R1.Freedate) As Datediff From (Select R0.d_Date As Freedate, R1.Datetype, Min(Date_Format(R2.Freedate, '%Y-%m-%d')) As Next_Freedate From Dim_d_Day R0 Left Join c_Freedate R1 On R0.d_Date = Date_Format(R1.Freedate,'%Y-%m-%d') And R1.Datetype In ('PA0001', 'PA0000') Left Join c_Freedate R2 On R1.Freedate < R2.Freedate And R2.Datetype = 'PA0001' Where R0.d_Date = Date_Format(Now(), '%Y-%m-%d') Group By Date_Format(R1.Freedate, '%Y-%m-%d'),R0.d_Date,R1.Datetype) R1", "dataSource");
                if (freedateList.size() > 0) {
                    Map freedateMap = freedateList.get(0);
                    String checkFreedate = freedateMap.get("datetype");
                    log.debug("是否交易日:" + checkFreedate + "|" + trading_day);
                    if (checkFreedate == "PA0000" && trading_day == "true") {
                        log.debug("线程号：" + content + "当前配置为仅交易日执行，跳过本次执行" + time);
                        String upThreadStatusTwo = "update Elitethread set expand='0' where content='" + content + "'";
                        eliteBean.update(upThreadStatusTwo, "dataSource");
                        return 1;
                    }
                }
                log.debug("配置表-线程号：" + rec_guid + "|执行周期：" + dateselect + "|执行时间间隔：" + time_interval + "|数据表名：" + table_name + "|任务标识：" + identification + "|任务类型：" + task_type + "|任务内容：" + identificationContent);
                log.debug("计划表-线程号：" + contentPlan + "|执行周期：" + execution_cycle + "|执行时间间隔：" + execution_interval + "|上次执行时间：" + prev_fire_time);

                if (KHUtil.isNull(rec_guid)) {
                    log.debug("线程号：" + rec_guid + "未查询到有效的规则配置");
                } else {
                    int ctime = 0;
                    if (dateselect == "minute") {
                        ctime = 60;
                    } else if (dateselect == "hour") {
                        ctime = 3600;
                    } else if (dateselect == "day") {
                        ctime = 86400;
                    } else if (dateselect == "month") {
                        ctime = 2626560;
                    } else if (dateselect == "year") {
                        ctime = 31536000;
                    }

                    //根据开始时间、周期、间隔计算与当前时间最近一次的执行时间和下次执行时间
                    String checkSql = "select DATE_ADD('" + check_starttime + "',INTERVAL floor(((TIMESTAMPDIFF(second,'" + check_starttime + "',now()))/" + ctime + ")/" + time_interval + ")*" + time_interval + " " + dateselect + ") as plan_prev_fire_time";
                    List checkList = eliteBean.chaxun_sql(checkSql, "dataSource");
                    String checkTime = checkList.get(0).get("plan_prev_fire_time"); //本次执行时间
                    log.debug("本次执行时间:" + checkTime);
                    if (!KHUtil.isNull(checkTime)) {
                        String checkPlanSql = "select count(*) as con from pa_execution_plan where content='" + rec_guid + "'  and prev_fire_time='" + checkTime + "' order by prev_fire_time desc limit 1";
                        List checkPlanList = eliteBean.chaxun_sql(checkPlanSql, "dataSource");
                        int con = checkPlanList.get(0).get("con"); //本次执行时间
                        if (time >= checkTime && con <= 0) {
                            //当前时间大于等于本次执行时间开始执行
                            log.debug("线程号：" + content + "当前时间" + time + "大于等于计划执行时间" + checkTime + "满足条件开始本次执行");
                            SyncData(eliteBean, rec_guid, table_name, identification, task_type, identificationContent, dateselect, time_interval, checkTime);
                        } else {
                            log.debug("线程号：" + rec_guid + "当前时间为:" + time + "|未到执行时间" + checkTime);
                        }
                    } else {
                        log.debug("线程号：" + rec_guid + "计算时间为空");
                    }
                }
            } else {
                log.debug("当前线程任务不在执行时间范围内");
            }

            }else{
                log.debug("当前线程任务不在执行时间范围内:"+"配置表-线程号:"+check_rec_guid+"|开始执行时间时分秒:"+time2+"|"+"结束执行时间时分秒："+time4+"|当前时间时分秒："+time3);

            }

        } catch (Exception e) {
            log.debug("【执行结束】同步平安任务异常" + e.getMessage());
        }
        //将当前线程更新为可执行状态0
        String upThreadStatus = "update Elitethread set expand='0' where content='" + content + "'";
        eliteBean.update(upThreadStatus, "dataSource");
        return 1
    }

    //将配置表数据同步至任务表，调用任务下发接口  //todo 确认资金账号、手机号码、确定任务类型 | 跟经营原有任务冲突解决办法
    public static boolean SyncData(EliteBean eliteBean, String content, String table_name, String markField, String task_type, String markContent, String dateselect, String time_interval, String prev_fire_time) {
        boolean sre_sync = false;
        //处理头文件
        Map<String, String> headerMap = new HashMap<String, String>();
        headerMap.put("Accept", "application/json");
        headerMap.put("Content-Type", "application/json");
        String msg = "";
        String TGuid = "";
        try {
            String conditionSql = "";
            //任务标识字段及内容
            if (!KHUtil.isNull(markField) && !KHUtil.isNull(markContent)) {
                conditionSql = "and a." + markField + "=" + "'" + markContent + "'";
                log.debug("查询条件" + conditionSql)
            }
            if (task_type == "apijy") {
                TGuid = KHUtil.getRandomString(36).toUpperCase();
                //经营
                String TaskSQl1 = "INSERT INTO account_information(rec_id, task_guid, customerid, task_type, source, createtime, deal_flag,thread_id) SELECT uuid(),uuid(),a.investorid,'" + content + "','3',now(),'0','" + content + "'  FROM dws." + table_name + " a left join account_information b on a.investorid=b.customerid and b.thread_id='" + content + "' where (b.customerid is null or b.customerid='')" + conditionSql;
                int taskRow1 = eliteBean.update(TaskSQl1, "dataSource");
                log.debug("线程号：" + content + "本次新增经营任务：" + taskRow1);
                log.debug("线程号：" + content + "|" + TGuid + "开始调用经营任务下发接口-----");
                String woOperationSendURL1 = KHDBConfig.getAPIURL(eliteBean, "API-InnerDomain") + "/apiTaskAssignJy" + "?threadid=" + content + "&TGuid=" + TGuid;
                String postResult1 = Util.doHttpGetUseHead(woOperationSendURL1, "UTF-8", 3600000, 0, headerMap);
                log.debug("经营任务下发接口返回结果：" + postResult1);
                JSONObject reJson = JSONObject.fromObject(postResult1);
                msg = reJson.getString("msg");

            } else if (task_type == "apidx") {
                TGuid = KHUtil.getRandomString(36).toUpperCase();
                //电销
                String TaskSQl2 = "INSERT INTO account_information(rec_id, task_guid, task_type, source, createtime, deal_flag,thread_id,mobile) SELECT uuid(),uuid(),'" + content + "','3',now(),'0','" + content + "',a.mobile  FROM dws." + table_name + " a left join account_information b on a.mobile=b.mobile and b.thread_id='" + content + "' where (b.mobile is null or b.mobile='') " + conditionSql;
                int taskRow2 = eliteBean.update(TaskSQl2, "dataSource");
                log.debug("线程号：" + content + "本次新增电销任务：" + taskRow2);
                log.debug("线程号：" + content + "|" + TGuid + "开始调用电销任务下发接口-----");
                String woOperationSendURL2 = KHDBConfig.getAPIURL(eliteBean, "API-InnerDomain") + "/apiTaskAssignDx" + "?threadid=" + content + "&TGuid=" + TGuid;
                String postResult2 = Util.doHttpGetUseHead(woOperationSendURL2, "UTF-8", 3600000, 0, headerMap);
                log.debug("电销任务下发接口返回结果：" + postResult2);
                JSONObject reJson = JSONObject.fromObject(postResult2);
                msg = reJson.getString("msg");

            } else if (task_type == "apisms") {
                TGuid = KHUtil.getRandomString(36).toUpperCase();
                //短信
                log.debug("线程号：" + content + "|" + TGuid + "开始调用短信任务创建接口-----");
                String woOperationSendURL3 = KHDBConfig.getAPIURL(eliteBean, "API-InnerDomain") + "/apiTaskSms" + "?threadid=" + content + "&TGuid=" + TGuid;
                String postResult3 = Util.doHttpGetUseHead(woOperationSendURL3, "UTF-8", 3600000, 0, headerMap);
                log.debug("短信发送接口返回结果：" + postResult3);
                JSONObject reJson = JSONObject.fromObject(postResult3);
                msg = reJson.getString("msg");
            } else if (task_type == "apifw") {
                TGuid = KHUtil.getRandomString(36).toUpperCase();
                //服务任务
                String TaskSQl2 = "INSERT INTO account_information(rec_id, task_guid, task_type, source, createtime, deal_flag,thread_id,mobile) SELECT uuid(),uuid(),'" + content + "','3',now(),'0','" + content + "',a.mobile  FROM dws." + table_name + " a left join account_information b on a.mobile=b.mobile and b.thread_id='" + content + "' where (b.mobile is null or b.mobile='') " + conditionSql;
                int taskRow2 = eliteBean.update(TaskSQl2, "dataSource");
                log.debug("线程号：" + content + "本次新增服务任务：" + taskRow2);
                log.debug("线程号：" + content + "|" + TGuid + "开始调用服务任务下发接口-----");
                String woOperationSendURL2 = KHDBConfig.getAPIURL(eliteBean, "API-InnerDomain") + "/apiTaskAssignFw" + "?threadid=" + content + "&TGuid=" + TGuid;
                String postResult4 = Util.doHttpGetUseHead(woOperationSendURL2, "UTF-8", 3600000, 0, headerMap);
                log.debug("服务任务下发接口返回结果：" + postResult4);
                JSONObject reJson = JSONObject.fromObject(postResult4);
                msg = reJson.getString("msg");
            }
            sre_sync = true;



        } catch (Exception e) {
            sre_sync = false;
            msg = content + "创建任务异常" + e.getMessage();
            log.debug(msg);
        }
        if (KHUtil.isNull(TGuid)) {
            TGuid = KHUtil.getRandomString(36).toUpperCase();
        }
        String planHisSql = "INSERT INTO pa_execution_plan(id, content, execution_cycle, prev_fire_time, next_fire_time, createddate, modifydate,execution_interval,deal_result) VALUES ('" + TGuid + "', '" + content + "', '" + dateselect + "', '" + prev_fire_time + "', date_add('" + prev_fire_time + "',INTERVAL " + time_interval + " " + dateselect + "), now(), now(),'" + time_interval + "','" + msg + "')";
        eliteBean.update(planHisSql, "dataSource");
        return sre_sync;
    }

}
